<template>
  <el-dialog :title="addForm && addForm.id ? '编辑商品' : '添加商品'" v-model="dialogVisble" width="70%" class="dialogBox"
    :before-close="closeBox">
    <div class="dialogBox">
      <el-form ref="formRef" style="max-width:800px" :model="addForm" :rules="roleRules" label-width="auto"
        class="demo-dynamic">
        <!--切换头-->
        <div class="tab-head">
          <div class="th-item" v-for="(tab, index) in tabList" :key="index" :class="tabId == tab.id ? 'th-item-ac' : ''">
            <div class="th-i-name" @click="tabChoose(tab.id)" :class="tabId == tab.id ? 'th-i-name-ac' : 'th-i-name-nor'">{{
              tab.name }}</div>
          </div>
        </div>
        <!--商品基本信息-->
        <div class="" v-show="tabId == 1">
          <el-form-item prop="cate_id" :label="'分组'">
            <el-select v-model="addForm.cate_id" placeholder="选择分组" clearable size="large"
              style="width: 240px; margin-right: 10px">
              <el-option v-for="item in cateArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item prop="title" label="标题">
            <el-input v-model="addForm.title" />
          </el-form-item>

          <el-form-item prop="sn" label="型号">
            <el-input v-model="addForm.sn" />
          </el-form-item>

          <el-form-item label="封面" prop="thumb">
            <div class="up-img-box">
              <el-image style="width: 100px; height: 100px" :src="addForm.thumb" fit="cover"
                :preview-src-list="[addForm.thumb]" />
              <div class="up-btn-box" @click="uploadImage">
                <input v-show="false" type="file" ref="fileInput" accept="image/*" @change="handleFileUpload" />
                <el-icon class="thumb-uploader-icon">
                  <Plus />
                </el-icon>
              </div>
            </div>
          </el-form-item>

          <el-form-item prop="description" label="简述">
            <el-input v-model="addForm.description" type="textarea" />
          </el-form-item>

          <el-form-item prop="sort" label="排序">
            <el-input v-model="addForm.sort" :value="addForm.sort ? addForm.sort : '9999'" />
            <el-text class="mx-1" type="info">数字越小排序越靠前</el-text>
          </el-form-item>

          <el-form-item label="状态" prop="state" v-if="addForm && addForm.id">
            <el-switch v-model="addForm.state" active-text="启用" inactive-text="禁用" />
          </el-form-item>

        </div>
        <!---相册-->
        <div class="" v-show="tabId == 2">
          <el-form-item label="相册" prop="photos">
            <div class="up-img-box">
              <el-image style="width: 100px; height: 100px;margin-right: 10px;border-radius: 5px;"
                v-for="value in addForm.photos" :src="value" fit="cover" :preview-src-list="addForm.photos" />
              <div class="up-btn-box" @click="uploadPhotos">
                <input v-show="false" type="file" ref="fileInputPhotos" accept="image/*" multiple
                  @change="handleFileUploadPhotos" />
                <el-icon class="thumb-uploader-icon">
                  <Plus />
                </el-icon>
              </div>
            </div>
          </el-form-item>
        </div>
        <!--详情-->
        <div class="" v-show="tabId == 3">
          <el-form-item label="详情" prop="text">
            <!-- 编辑器 自定义工具栏-->
            <!-- <quill-editor theme="snow" ref="myQuillEditor" v-model:content="addForm.text" :options="myEditorInit" content-type="html"></quill-editor> -->
            <!-- 编辑器 工具栏铺满-->
            <quill-editor theme="snow" ref="myQuillEditor" v-model:content="addForm.text" toolbar="full"
              content-type="html"></quill-editor>
            <!-- 使用自定义图片上传 -->
            <!-- <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" /> -->
          </el-form-item>
        </div>

        <!--规格属性-->
        <div class="" v-show="tabId == 4">
          <!---选择单一还是多规格 默认单规格-->
          <div class="mb-2 ml-4">
            <el-form-item label="类型" prop="attrType">
              <el-radio-group v-model="attrType" @change="chooseAttrType">
                <el-radio value="1" size="large">单规格</el-radio>
                <el-radio value="2" size="large">多规格</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <!--单一属性 但规格-->
          <div class="" v-show="attrType == '1'">
            <el-form-item prop="g_inventory" label="库存">
              <el-input v-model="attrSingle.g_inventory" />
            </el-form-item>
            <el-form-item prop="g_original" label="原价">
              <el-input v-model="attrSingle.g_original" />
            </el-form-item>
            <el-form-item prop="g_price" label="售价">
              <el-input v-model="attrSingle.g_price" />
            </el-form-item>
          </div>
          <div class="" v-show="attrType == '2'">
            <attrView ref="attrViewRef" />
          </div>
        </div>

      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeBox">取 消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, reactive, getCurrentInstance, nextTick, watch, toRaw } from "vue";
import attrView from './attribute.vue'; //属性规格
import { ElMessage, FormInstance } from "element-plus";
import { QuillEditor } from '@vueup/vue-quill'; //quill 编辑器
import '@vueup/vue-quill/dist/vue-quill.snow.css';//编辑器模板样式
import { Value } from "sass";


const currentInstance = getCurrentInstance(); //获取main.js中挂载的实例
const { $api } = currentInstance.appContext.config.globalProperties;

const pors = defineProps({
  showdialog: {
    type: Boolean,
    default: false,
  },
  list: {
    type: Object,
    default: {},
  },
  cateArr: {
    type: Array,
    default: [{ name: "请选择用户组", id: 0 }],
  },
});
//规格类型
const attrType = ref("1"); //默认选中单规格
//单一的规格值
const attrSingle = ref({
  g_price: 1,
  g_original: 1,
  g_inventory: 1,//库存 原价 售价
});

//tabs 切换
const tabList = ref([{ id: 1, name: '信息' }, { id: 2, name: '相册' }, { id: 3, name: '详细' }, { id: 4, name: '规格' }]);
const tabId = ref(1); //选中值
const tabChoose = (id) => {
  tabId.value = id;
};// 选中标签

const formRef = ref<FormInstance>(); //定义form
//表单提交元素
const addForm = computed(() => pors.list);


const fileInput = ref(null); //主图上传控件
const fileInputPhotos = ref(null); //相册上传

//表单元素的规则
const roleRules = reactive({
  title: [
    {
      required: true,
      message: "请输入标题",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
  sn: [
    {
      required: true,
      message: "请输入商品型号",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
  cate_id: [
    {
      required: true,
      message: "请选择分组",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
  thumb: [
    {
      required: true,
      message: "请上传商品主图",
      trigger: "blur",//商品主图
    }
  ],
  text: [
    {
      required: true,
      message: "请填写内容",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
});

const emits = defineEmits(["useConfirm", "useClose"]); //定义一个或多个自定义按钮事件 传递到父组件

const dialogVisble = ref(false); // 定义控制弹窗显隐的变量

const myQuillEditor = ref();//编辑器
//编辑器内容回显
// watch(
//   () => pors.list.text,
//   (newVal) => {
//     // console.log(newVal,"新值");
//     nextTick(()=>{
//       toRaw(myQuillEditor.value).setHTML = newVal; //值变更时赋值
//     });
//   }
// );

//关闭模态框
const closeBox = () => {
  // if (!formRef.value) return;
  // formRef.value.resetFields();
  dialogVisble.value = false; //重置为空
  emits("useClose", dialogVisble.value);
  tabId.value = 1;
};

//确定/提交
const submitForm = (formData: FormInstance | undefined) => {
  if (!formData) return;
  //校验
  formData.validate((valid) => {
    if (valid) {
      // console.log();

      dialogVisble.value = false;
      // console.log(addForm.value,"提交的数据");
      emits("useConfirm", addForm.value);
      formData.resetFields(); //重置为空
      tabId.value = 1;
    } else {
      // console.log("error submit!");
      return false;
    }
  });
};

//主图图片上传
const uploadImage = () => {
  fileInput.value.click();
};
//input 点击事件
const handleFileUpload = (event) => {
  // console.log(event,"55");
  // file.value = event.target.files[0]; // 上传的内容
  var sizeLenght = event.target.files[0].size; //文件大小
  var size = sizeLenght / (1024 * 1024);
  // state.fileSize = size.toFixed(2); //文件大小 四舍五入保留小数后两位
  // state.fileName = event.target.files[0].name; // 文件名称
  // state.isUpLoad = true;

  // var maxlenght = 1020*1020*5; //未登录则最大5M
  // if (state.isLogin) {
  //   maxlenght = 1020*1020*20; //登录则最大20M
  // }
  // //大于100M时返回
  // if (sizeLenght > maxlenght) {
  //   // console.log("文件太大",state.fileSize/(1024*1024));
  //   msg({ type: "warn", text: "文件太大" });
  //   state.isUpLoad = false;
  //   return false;
  // }
  upFileService(event); //上传到服务器
  //   console.log(event.target.files[0]);
};

//提交到服务器
const upFileService = (event) => {
  const formdata = new FormData();
  formdata.append("file", event.target.files[0]); //转为文件流
  formdata.append("name", event.target.files[0].name); //文件名称参数
  formdata.append("folder", "article_img")
  $api.file_post("v1/login/upload/images", formdata).then((res) => {
    if (res.code == 200) {
      addForm.value.thumb = res.data;
    }
  });

};
//相册上传
const uploadPhotos = () => {
  fileInputPhotos.value.click(); //点击事件
}
//上传上传input 选中的图片点击事件
const handleFileUploadPhotos = (event) => {
  const files = (event.target as HTMLInputElement).files;
  console.log(files, "选中的")
  if (!files) return;
  addForm.value.photos = [];
  Array.from(files).forEach(file => {
    if (!file.type.startsWith('image/')) return;
    addForm.value.photos.push(URL.createObjectURL(file));
  });
}
// 编辑器
const myEditorInit = ref({
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],//加粗 斜体 下划线 删除线
      ['blockquote', 'code-block'],//引用
      [{ 'size': ['small', false, 'large', 'huge'] }], //字体大小
      // [{ 'size': ['12px','13px','14px','15px','18px','36px']}], //字体大小
      [{ 'font': [] }],//字体
      [{ 'align': [] }],//对齐方式
      [{ 'list': 'ordered' }, { 'list': 'bullet' }], //列表 有序 无序
      [{ 'indent': '-1' }, { 'indent': '+1' }], //缩进
      [{ 'script': 'sub' }, { 'script': 'super' }],//上标 下标
      [{ 'header': 1 }, { 'header': 2 }], //标题
      ['link', 'image', 'video'], //连接 图片 视频
      [{ 'direction': 'rtl' }], //文本方向
      [{ 'color': [] }, { 'background': [] }], //字体颜色 背景颜色
      ['clean'] //清除文本格式
    ],//工具栏
  },
  placeholder: '请输入内容...'
});

//选中规格类型（1单规格2多规格）
const chooseAttrType = (e)=>{
  if(e == '1'){ //单规格

  }else{
    //多规格
    
  }
  console.log(e)
}

// 将变量暴露出来
defineExpose({
  dialogVisble
});
</script>
<style>
.el-overlay {
  position: absolute;
}

.el-overlay-dialog {
  position: absolute;
}

.dialogBox {
  width: calc(100% - 40px);
  min-height: 95%;
  max-height: 99%;
  padding: 10px;
  position: absolute;
  left: 0;
  right: 0;
  margin: 20px;
}

.up-img-box {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.up-btn-box {
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border: 1px solid #ddd;
  margin-left: 30px;
}

.ql-editor {
  max-height: 350px !important;
}

.ql-container {
  width: 100%;
}

.demo-tabs-editor {
  min-height: 600px;
}

.demo-tabs-editor .el-tabs__content {
  min-height: 520px;
}

.tab-head {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #f1f1f1;
}

.th-item {
  padding: 10px;
}

.th-item-ac {
  border-bottom: 1px solid #409eff;
}

.th-i-name {
  cursor: pointer;
  font-size: 15px
}

.th-i-name-nor {
  color: #999
}

.th-i-name-ac {
  color: #409eff;
  font-weight: bold;
}

.el-dialog__footer {
  position: absolute;
  right: 10px;
  bottom: 10px;
}

.dialog-footer {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.el-button+.el-button {
  margin-left: 10px;
}
</style>
